package com.xzc.shopping.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xzc.shopping.common.BaseResponse;
import com.xzc.shopping.common.ErrorCode;
import com.xzc.shopping.common.ResultUtils;
import com.xzc.shopping.mapper.CartMapper;
import com.xzc.shopping.mapper.ProductMapper;
import com.xzc.shopping.model.domain.Cart;
import com.xzc.shopping.model.domain.Product;
import com.xzc.shopping.model.domain.User;
import com.xzc.shopping.model.dto.CartAddDTO;
import com.xzc.shopping.model.vo.CartListVO;
import com.xzc.shopping.model.vo.CartVO;
import com.xzc.shopping.service.CartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

import static com.xzc.shopping.constant.UserConstant.USER_LOGIN_STATE;

/**
* @author Administrator
* @description 针对表【cart】的数据库操作Service实现
* @createDate 2025-02-26 11:15:14
*/
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart>
implements CartService {

    @Resource
    private  CartMapper cartMapper;
    @Autowired
    private ProductMapper productMapper;



    // 删除购物车项
    @DeleteMapping("/{cartId}")
    public BaseResponse<Boolean> deleteCartItem(@PathVariable Long cartId,
                                                HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (user == null) {
            return ResultUtils.error(ErrorCode.NOT_LOGIN);
        }
        return this.deleteCartItem(user.getId(), cartId);
    }

    @Override
    public BaseResponse<List<CartVO>> getCartList(Integer userId) {
        // 查询基础购物车数据
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<Cart> cartList = this.list(queryWrapper);

        // 关联商品信息
        List<CartVO> voList = cartList.stream().map(cart -> {
            Product product = productMapper.selectById(cart.getProductId());

            CartVO vo = new CartVO();
            vo.setProductId(product.getId());
            vo.setProductName(product.getName());
            vo.setProductPrice(product.getPrice());
            vo.setQuantity(cart.getQuantity());
            return vo;
        }).collect(Collectors.toList());

        return ResultUtils.success(voList);
    }

    @Override
    public BaseResponse<Boolean> addCartItem(Integer userId, CartAddDTO cartAddDTO) {
        // 查询是否已存在购物车项
        Cart existItem = cartMapper.selectOne(new LambdaQueryWrapper<Cart>()
                .eq(Cart::getUserId, userId)
                .eq(Cart::getProductId, cartAddDTO.getProductId()));
        int result ;
        if (existItem != null) {
// 存在则更新数量
            existItem.setQuantity(existItem.getQuantity() + cartAddDTO.getQuantity());
            result = cartMapper.updateById(existItem);
        }else{
            Cart cart = new Cart();
            BeanUtils.copyProperties(cartAddDTO, cart);
            cart.setUserId(userId);
//            cart.setQuantity(1);
            // 新增记录
            result = cartMapper.insert(cart);
        }
        if(result == 1){
            return ResultUtils.success(true);
        }else{
            return ResultUtils.error(ErrorCode.INSERT_ERROR);
        }
    }

    @Override
    @Transactional
    public BaseResponse<Boolean> deleteCartItem(Integer userId, Long cartId) {
        boolean exists = lambdaQuery()
                .eq(Cart::getId, cartId)
                .eq(Cart::getUserId, userId)
                .exists();
        if (!exists) {
            return ResultUtils.error(ErrorCode.NOT_FOUND_ERROR, "购物车项不存在");
        }
        return removeById(cartId) ? ResultUtils.success(true) : ResultUtils.error(ErrorCode.OPERATION_ERROR);
    }

    // 更新数量（带乐观锁）
    @Transactional
    @Override
    public BaseResponse<CartListVO> updateQuantity(Integer userId, Long cartId, Integer quantity) {
        // 校验用户权限
        Cart cart = getOne(new LambdaQueryWrapper<Cart>()
                .eq(Cart::getId, cartId)
                .eq(Cart::getUserId, userId));
        if (cart == null) {
            return ResultUtils.error(ErrorCode.NOT_FOUND_ERROR);
        }

        // 带乐观锁更新
        cart.setQuantity(quantity);
        return getLatestCartList(userId);
    }
    // 获取最新购物车数据
    private BaseResponse<CartListVO> getLatestCartList(Integer userId) {
        List<CartVO> items = cartMapper.selectCartList(userId);
        CartListVO cartListVO = new CartListVO(items);
        return ResultUtils.success(cartListVO);
    }
}
